﻿using Microsoft.Extensions.DependencyInjection;
using WebApiClientCore;
using WebApiClientCore.Serialization.JsonConverters;

namespace AiQiuQuan.Sport.Core
{
    /// <summary>
    /// webapiclientcore
    /// </summary>
    public static class WebApiClientCoreExtensions
    {
        /// <summary>
        /// 注入WebApiClientCore 相关服务
        /// </summary>
        /// <param name="services">IServiceCollection</param>
        /// <param name="assembyNameArray">client服务所在程序集名称，比如:Handday.Scrm.Client</param>
        public static IServiceCollection AddWebApiClientCore(this IServiceCollection services, params string[] assembyNameArray)
        {
            if (assembyNameArray == null || assembyNameArray.Length == 0)
            {
                return services;
            }

            var assemblyList = AppDomain.CurrentDomain.GetAssemblies().Where(m => ValidateAssembly(m.FullName, assembyNameArray)).ToList();
            if (assemblyList.Count > 0)
            {
                services.AddTransient<TraceDelegatingHandler>();
                services.AddWebApiClient().ConfigureHttpApi((options, serviceProvider) =>
                {
                    options.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
                    options.JsonSerializeOptions.WriteIndented = false;
                    options.JsonDeserializeOptions.Converters.Add(new NumberConverter());
                });

                foreach (var item in assemblyList)
                {
                    var typeList = item.GetTypes().Where(t => t.IsPublic && t.IsInterface && t.IsAssignableTo(typeof(IHttpApi))).ToList();
                    typeList.ForEach(type =>
                    {
                        services.AddHttpApi(type).AddHttpMessageHandler<TraceDelegatingHandler>();
                    });
                }
            }

            return services;
        }

        #region private methods
        /// <summary>
        /// 验证传入程序集名是否在当前域
        /// </summary>
        private static bool ValidateAssembly(string fullName, string[] assembyNameArray)
        {
            foreach (var item in assembyNameArray)
            {
                if (fullName.Contains(item))
                {
                    return true;
                }
            }

            return false;
        }
        #endregion
    }
}
